import os, sys
from datetime import datetime

import torch

root_path = os.getcwd()
sys.path.insert(0, root_path + "/YOLO")
import json
import time
import detect
import requests
import asyncio
import websockets

HOST = '172.20.97.170'
PORT = 8080
ADDR = (HOST, PORT)
BUFFSIZE = 1024
MAX_LISTEN = 50

TEETH_DETECT = 2


async def handler(websocket):
    msg = await websocket.recv()
    processed_msg = await process_recv(msg, websocket)
    await websocket.send(processed_msg)


async def process_recv(recv_msg,_websocket):
    print('接收数据长度为：{}'.format(len(recv_msg)))
    msg_dict = json.loads(recv_msg)
    # 发送请求数据
    #await _websocket.send(json.dumps("你好！这里是AI小齿"))
    print('发送返回完毕！！！')
    opcode = msg_dict["opcode"]
    subcode = msg_dict["subcode"]
    data = msg_dict["content"]
    other = msg_dict["other"]

    openid = other["openid"]
    username = other["name"]
    looktime = other["time"]
    save_route=other["imgurl"]
    print('主操作码：', opcode, ' 子操作码：', subcode, ' 其他信息：', f"{openid}{username}{looktime}")
    msg_json = ""
    msg = {}
    if opcode == TEETH_DETECT and subcode == 0:
        print("进行TEETH_DETECT")
        result = process_image_data(data)
        if (result is None):
            usermessage = "健康"
        else:
            usermessage = f"亚健康"
        print(f"数组为{str(result)}")
        requests.post("https://www.aistomatology.cn/wx/sendmessage",
                      data={'code': openid, 'name': username, 'message': usermessage, 'time': looktime,'result':str(result),'imgurl':save_route})
        msg = {"opcode": opcode, "subcode": subcode, "content": result,"other": "检测完毕"}

    if len(msg) > 0:
        msg_json = json.dumps(msg)
    return msg_json


def process_image_data(data):
    return detect.predict(data)

if __name__ == '__main__':
    print("AI小齿服务器启动")
    start_server = websockets.serve(handler, host=HOST, port=PORT, max_size=8 * 1024 * 1024)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
